package ru.poomsae.isap.Online.SystemCut

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.JSONObjectRequestListener
import com.example.isap_wtf.Model.ApiEndPoint
import com.example.isap_wtf.Model.ParametrsISAP
import ru.poomsae.isap.VivOcenActivity
import org.json.JSONObject
import ru.poomsae.isap.R


class PresentationActivity : AppCompatActivity() {

    var s = 20
    var r = 20
    var e = 20
    var pr: Double = 6.0
    var accy: Double = 4.0
    var tot: Double = 10.0
    var onlineConSys = ParametrsISAP.onlineConSys
    open var accyInt = 40
    var prInt = 60
    var str = ""
    var idsud = ""
    var mIDHost = ParametrsISAP.idHostServer
    var idvistuplenie = ParametrsISAP.idvistuplenie
    var numSud = ParametrsISAP.numSud
    var sudID = ParametrsISAP.sudID

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.presentation)
        accy = intent.getDoubleExtra("accuracyDouble", 4.0)
        val accyr = findViewById<TextView>(R.id.accyr)
        accyr.setText(accy.toString())
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
        getSupportActionBar()?.hide()

        var device: UsbDevice
        var nodevices = true

        val mUsbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val deviceList: HashMap<String, UsbDevice> = mUsbManager.getDeviceList()
        val deviceIterator: Iterator<UsbDevice> = deviceList.values.iterator()
        val send = findViewById<Button>(R.id.send)
        println("PresentationActivity nodevices = " + nodevices)
//        while (deviceIterator.hasNext()) {
//            nodevices = false
//            device = deviceIterator.next()
//            send.visibility = View.GONE
//        }
        println("PresentationActivity nodevices = " + nodevices + " send.visibility = " + send.visibility)
        if (nodevices) {
            send.visibility = View.VISIBLE
        }

        send.setOnClickListener {
            if (onlineConSys == 0) {
                val intent = Intent(this, SystemOfCut::class.java)
                startActivity(intent)
                finish()
            }

            if (onlineConSys == 1) {
                accyInt = (accy * 10).toInt()
                prInt = (pr * 10).toInt()
                zapisOCen()
            }
        }

        val sila = findViewById<RadioGroup>(R.id.sila)
        val silaPres = findViewById<TextView>(R.id.silaPres)
        val total = findViewById<TextView>(R.id.total)
        val pres = findViewById<TextView>(R.id.pres)
        sila.setOnCheckedChangeListener(
            RadioGroup.OnCheckedChangeListener { group, checkedId ->
                val radio: RadioButton = findViewById(checkedId)
                s = ((radio.text as String).toDouble() * (10).toDouble()).toInt()
                silaPres.setText(radio.text as String)
                pr = (s + r + e).toDouble()/(10).toDouble()
                pres.setText(pr.toString())
                tot = accy + pr
                total.setText(String.format("%.1f",tot))
            })

        val ener = findViewById<RadioGroup>(R.id.ener)
        val enerPres = findViewById<TextView>(R.id.enerPres)
        ener.setOnCheckedChangeListener(
            RadioGroup.OnCheckedChangeListener { group, checkedId ->
                val radio: RadioButton = findViewById(checkedId)
                e = ((radio.text as String).toDouble() * (10).toDouble()).toInt()
                enerPres.setText(radio.text as String)
                pr = (s + r + e).toDouble()/(10).toDouble()
                pres.setText(pr.toString())
                tot = accy + pr
                total.setText(String.format("%.1f",tot))
            })

        val rhyt = findViewById<RadioGroup>(R.id.rhyt)
        val rhytmPres = findViewById<TextView>(R.id.rhytmPres)
        rhyt.setOnCheckedChangeListener(
            RadioGroup.OnCheckedChangeListener { group, checkedId ->
                val radio: RadioButton = findViewById(checkedId)
                r = ((radio.text as String).toDouble() * (10).toDouble()).toInt()
                rhytmPres.setText(radio.text as String)
                pr = (s + r + e).toDouble()/(10).toDouble()
                pres.setText(pr.toString())
                tot = accy + pr
                total.setText(String.format("%.1f",tot))
            })

    }

    fun addOcen() {
        val intent = Intent (this, VivOcenActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        str = event.toString()
        str = str.substringAfter(',')
        str = str.substringBefore(',')
        str = str.replace(" keyCode=KEYCODE_", "")
        if (!str?.equals("ENTER")) {
            idsud = idsud + str
            if (idsud.length == 10) {
                ParametrsISAP.sudID = idsud
                idsud = ""
                confirmation()
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    fun confirmation() {
        val idserverDialog = AlertDialog.Builder(this)
        idserverDialog.setTitle("Send ratings" + "\n" + "Judges card = " + ParametrsISAP.sudID)
        idserverDialog.setMessage("Accuracy = " + accy + "\n" + "Presentation = " + pr)
        idserverDialog.setPositiveButton("OK", {dialogInterface: DialogInterface, i: Int -> })
        idserverDialog.setNeutralButton("Neutral", {dialog: DialogInterface?, which: Int ->  })
        idserverDialog.setNegativeButton("Cancel", {dialog: DialogInterface?, which: Int ->  })
        val idserverCustom = idserverDialog.create()
        idserverCustom.show()
        idserverCustom.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
            accyInt = (accy * 10).toInt()
            prInt = (pr * 10).toInt()
            Toast.makeText(this, "Judges card = " + ParametrsISAP.sudID,
                Toast.LENGTH_LONG).show()
            zapisOCen()
        }
        idserverCustom.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
            idserverCustom.dismiss()
        }
        idserverCustom.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
            Toast.makeText(this, "Judges card = " + ParametrsISAP.sudID,
                Toast.LENGTH_LONG).show()
        }
    }

    fun zapisOCen() {
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.ADDOCENKIA)
            .addBodyParameter("vistuplenie_idvistuplenie", idvistuplenie)
            .addBodyParameter("ocenki_nomsud", numSud)
            .addBodyParameter("sudID", ParametrsISAP.sudID)
            .addBodyParameter("ocenki_t", accyInt.toString())
            .addBodyParameter("ocenki_p", prInt.toString())
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    val success = response?.getInt("success")
                    Toast.makeText(applicationContext,"Judge  № " + numSud + " scores sent successfully success = " + success,
                        Toast.LENGTH_SHORT).show()
                    addOcen()
                }
                override fun onError(anError: ANError?) {
                    Toast.makeText(applicationContext,"Error judge  № " + numSud + " scores sent successfully",
                        Toast.LENGTH_SHORT).show()
                }
            })
    }
}